package com.wh.springboot.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.springboot.common.Constants;
import com.wh.springboot.common.Result;
import com.wh.springboot.common.entity.BanJi;
import com.wh.springboot.common.entity.XueYuan;
import com.wh.springboot.common.entity.dto.UserDTO;
import com.wh.springboot.service.IBanJiService;
import com.wh.springboot.service.IXueYuanService;
import com.wh.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.wh.springboot.service.IUserService;
import com.wh.springboot.common.entity.User;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author elsy
 * @since 2023-01-09
 */
@RestController
@RequestMapping("/user")
//允许跨域请求的域和允许设置和接收Cookie
@CrossOrigin
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private IBanJiService banJiService;
    @Resource
    private IXueYuanService xueYuanService;

    // 新增和修改
    @PostMapping
    public Result save(@RequestBody User user) {
        //新增或者更新
        return Result.success(userService.saveOrUpdate(user));
    }

    //  查询所有数据
    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
    }

    //查询当前用户表里面的所有的角色的用户
    @GetMapping("/role/{role}")
    public Result findUsersByRole(@PathVariable String role) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role", role);
        List<User> list = userService.list(queryWrapper);
        return Result.success(list);
    }

    //根据id查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    //删除数据
    @DeleteMapping("/{id}")//id 与下面的id必须一致
    //    @PathVariable 表示 url 这个参数
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }

    //批量删除
    @DeleteMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(userService.removeByIds(ids));
    }

    //分页查询
    //    接口路径:/user/page
    //    @RequestParam接收 ?pageNum=1&pageSize=10
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize, @RequestParam(defaultValue = "") String username,
                           @RequestParam(defaultValue = "") String nickname,
                           @RequestParam(defaultValue = "") String phone,
                           @RequestParam(defaultValue = "") String address) {


        //关联查询
        //1.第一种办法
//        if(StringUtils.isNotBlank(username)){
//            userService.loadUserByleftJoin(username,pageNum,pageSize);
//
//        }
        //①.mapper
//        @Select("select a.username,b.name FROM sys_user as a LEFT JOIN ban_ji as b ON a.ban_ji_id=b.id limit #{} #{}")


        //1.第二种办法
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //降序
//        queryWrapper.orderByDesc("id");

        //输入的值是非空的话，再执行
//        if (!"".equals(username)) {
//            queryWrapper.like("username", username);
//        }
//        if (!"".equals(nickname)) {
//            queryWrapper.like("nickname", nickname);
//        }
//        if (!"".equals(phone)) {
//            queryWrapper.like("phone", phone);
//        }
//        if (!"".equals(address)) {
//            queryWrapper.like("address", address);
//        }
//        获取当前用户信息
        User currentUser = TokenUtils.getCurrentUser();
        System.out.println("获取当前用户信息的昵称==================" + currentUser.getNickname());


//        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);

        Page<User> page = userService.findPage(new Page<>(pageNum, pageSize), username, nickname, phone, address);

        for (User user : page.getRecords()) {
            //为班级名字进行赋值
            if (user.getBanJiId() != null) {
                //班級banjiservice查库
                BanJi banji = banJiService.getById(user.getBanJiId());
                user.setBanJiName(banji.getName());

            }
            //为学院名字进行赋值
            if (user.getXueYuanId() != null) {
                //班級学院XueYuanservice查库
                XueYuan xueYuan = xueYuanService.getById(user.getXueYuanId());
                user.setXueYuanName(xueYuan.getName());
            }
            //为老师名字进行赋值
            if (user.getTeacherId() != null) {
                //老師XueYuanservice查库
                User teacher = userService.getById(user.getTeacherId());
                user.setTeacherName(teacher.getUsername());
            }
        }
//        return Result.success(userService.findPage(new Page<>(pageNum, pageSize), username, nickname, phone, address));
        return Result.success(page);
    }


    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
        // ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");

        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");
        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        //URLEncoder的方式进行编码
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        //刷新数据到输出流当中
        writer.flush(out, true);
        //此处记得关闭输出Servlet流
        out.close();
        // 关闭writer，释放内存
        writer.close();
    }

    /**
     * excel 导入
     *
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        //1.文件不能为空
        if (file.isEmpty()) {
            return Result.error(Constants.Status_500, "文件为空不能上传");
        }
        //2.POI或缺Excel解析数据
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        //3.第一一个程序集合，接收文件中的数据，解析数据，装到集合里面
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<User> list = reader.read(0, 1, User.class);

        userService.saveBatch(list);
        return Result.success(true);
    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO, HttpServletRequest request) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        String captcha = userDTO.getCaptcha();//验证码
        //校验为空

        //登陆成功利用session存储账号密码
        HttpSession session = request.getSession(true);
        String sessionCaptcha = (String) session.getAttribute("code");
        System.out.println("登录session：" + session.getAttribute("code"));
        System.out.println("登录获取的session：" + sessionCaptcha);

        //判断验证码是否为空,与验证码图标比对
        if (StrUtil.isNotBlank(captcha) && sessionCaptcha.equals(captcha)) {
            //校验不为空
            UserDTO dto = userService.login(userDTO);

            return Result.success(dto);
        }
        return Result.error(Constants.Status_400, "验证码错误！");
    }


    //注册
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        //校验为空
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.Status_400, "参数错误，页面无法访问");
        }
        return Result.success(userService.register(userDTO));

    }
//    //个人中心获取数据
//    @GetMapping("/{id}")
//    public User findOne(@PathVariable Integer id) {
//        return userService.getById(id);
//    }


    @GetMapping("/getCode")
    //验证码
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.验证码对象
        ///HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        //2.放入session
        HttpSession session = request.getSession(true);
        session.setAttribute("code", captcha.getCode());
        System.out.println("创建session：" + session.getAttribute("code"));
        //3.输入
        ServletOutputStream outputStream = response.getOutputStream();
        captcha.write(outputStream);
        //关闭输出流
        outputStream.close();
    }


}

